import React from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  StyleSheet,
  TextInput,
  Image,
  ImageBackground
} from 'react-native';
import { ImagePicker } from '@ant-design/react-native';
import FontAwesome from "react-native-vector-icons/FontAwesome";
import MaterialIcons from 'react-native-vector-icons/MaterialIcons';
import GlobalStyles from "../styles/GlobalStyles";
import HttpUtils from "../../expand/dao/HttpUtils";
import {BASE_URL} from '../BASE_URL';
import AuthUtil from '../AuthUtils';
import {launchImageLibrary}  from 'react-native-image-picker'

// fileUrl:/web-api/api/localStorage/uploadR
const upFileImg = BASE_URL.apiBaseUrl + '/api/localStorage/uploadR'

export default class FormItem extends React.Component {
  constructor(props) {
    super(props);
    const {value} = this.props;
    this.state = {
      textInput: value || '',
      files:[]
    };
  }

  onChange = (files, type, index) => {
    console.log("file")
    console.log(type)
    console.log(index)
    console.log(files)

    let formData = new FormData()
    for(var i = 0;i<files.length;i++){
      let file = {uri: files[i].url, type:"multipart/form-data",name:"image.jpg"};   //这里的key(uri和type和name)不能改变,
      formData.append("file",file);   //这里的files就是后台需要的key
    }
    console.log(formData)
    let that=this
    AuthUtil.getAuthParam().then((authHeader)=>{
      fetch(upFileImg, {
        headers: {
          'Content-Type':"multipart/form-data",
          ...authHeader,
        },
        method: "POST",
        body: formData,
      }).then((response)=>{
        return response.json();
      }).then((res)=>{
        that.props.onChange(res.picture_url)
        // res.picture_url
      })
    })
  }

  handleUseImage(){
    console.log("hit it")
    let options={
      mediaType:'photo',
      maxWidth:400,
      maxHeight:300,
      videoQuality:'',
      durationLimit:120,
      quality:1,
      cameraType:'back',
      includeBase64:false,
      saveToPhotos:true,
      selectionLimit:1,
    }
    let formData = new FormData()
    let that=this

    launchImageLibrary(options, function(opt){
      let files=opt.assets
      for(var i = 0;i<files.length;i++){
        let file = {uri: files[i].uri, type:"multipart/form-data",name:`${files[i].fileName||'img/jpg'}`};   //这里的key(uri和type和name)不能改变,
        formData.append("file",file);   //这里的files就是后台需要的key
      }
      console.log(files)
      AuthUtil.getAuthParam().then((authHeader)=>{
        fetch(upFileImg, {
          headers: {
            'Content-Type':"multipart/form-data",
            ...authHeader,
          },
          method: "POST",
          body: formData,
        }).then((response)=>{
          return response.json();
        }).then((res)=>{
          that.props.onChange(res.picture_url)
          // res.picture_url
        })
      })
    })
  }

  render() {
    const {
      label,
      onClick,
      hideIcon,
      iconFont,
      iconSize,
      labelWidth,
      readonly,
      isMust
    } = this.props;
   
    return (
      <View style={styles.item}>
        {/* <Text
          style={[
            styles.label,
            labelWidth ? {width: labelWidth} : {width: 100},
          ]}>
          {label}
        </Text> */}
        <View style={GlobalStyles.formRow}>
            { 
              isMust?
              (<FontAwesome  name={'asterisk'} color={'red'} size={8} style={GlobalStyles.formRowRequire}/>)
              :null
            }
            <Text
               style={[
                styles.label,
                labelWidth ? {width: labelWidth} : {width: 100},
              ]}
            >{label}</Text>
           
        </View>
        <View style={{flex: 1}}>
          <View style={styles.content}>
            {this.renderInput()}
            {hideIcon ? null : (
              <TouchableOpacity
                activeOpacity={0.7}
                onPress={() => (onClick != undefined ? onClick() : null)}>
                <MaterialIcons
                  name={iconFont ? iconFont : 'arrow-forward-ios'}
                  size={iconSize ? iconSize : 19}
                  color={'#209bf6'}
                />
              </TouchableOpacity>
            )}
          </View>
        </View>
      </View>
    )
  }
  renderInput() {
    const {
      placeholder,
      value,
      textPaddingLeft,
      type,
      multiline,
      onClick,
      numberOfLines,
      readonly
    } = this.props;
    const { files } = this.state;
    let height = 25;
    if (multiline) {
      height = 25 * numberOfLines;
    }
    // const {textInput} = this.state;
    this.state.textInput = value;
    if (type && type == 'input') {
      return (
        <TextInput
          value={value}
          placeholder={placeholder}
          multiline={multiline}
          numberOfLines={numberOfLines}
          readonly={readonly}
          onChangeText={(text) => {
            this.props.onchange(text);
            this.setState({textInput: text});
          }}
          style={[
            {
              width: 200,
              height: height,
              fontSize: 14,
              paddingTop: 0,
              paddingBottom: 0,
            },
            textPaddingLeft ? {marginLeft: textPaddingLeft} : {marginLeft: 5},
          ]}
        />
      );
    } else if(type && type == 'upload'){
      return(
        // onPress={()=>{
        //   this.handleUseImage()
        // }}
        <TouchableOpacity >
       {/* <TouchableOpacity style={{flexDirection:"row",flexWrap:"wrap"}}> */}
          {value&&value.length>0?
          // <Image
          //     style={{width:100,height:100}}
          //     source={{uri:BASE_URL.apiBaseUrl+value[0]}}
          // />
          this._uploadItem(value)
          :null}
          {/* <ImagePicker
            files={files}
            onChange={this.onChange}
            onImageClick={(index, fs) => console.log(index, fs)}
            selectable={files.length < 2}
            multiple={false}
          /> */}
          <View>
            <ImageBackground
               style={{
                width: 100,
                height: 100,
                alignItems:'center',
                justifyContent:"center",
                borderWidth:1,
                borderColor:"cacaca",
              }}
               source={require('../../assets/images/item/addIcon.png')}
            >
              <Text onPress={()=>{this.handleUseImage()}} style={{ width: 100, height: 100,}}> </Text>
            </ImageBackground>
          </View>
         

        </TouchableOpacity>
      )

    }else {
      if (value) {
        return (
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={() => (onClick != undefined ? onClick() : null)}>
            <Text
              style={[
                styles.value,
                textPaddingLeft
                  ? {paddingLeft: textPaddingLeft}
                  : {paddingLeft: 5},
              ]}>
              {value}
            </Text>
          </TouchableOpacity>
        );
      } else {
        return (
          <TouchableOpacity
            activeOpacity={0.7}
            onPress={() => (onClick != undefined ? onClick() : null)}>
            <Text
              style={[
                styles.placeholder,
                textPaddingLeft
                  ? {paddingLeft: textPaddingLeft}
                  : {paddingLeft: 5}
              ]}>
              {placeholder}
            </Text>
          </TouchableOpacity>
        )
      }
    }
  }

  _uploadItem(files){
    const views = []
    files.map((item,index)=>{
        let control; 
        control=(
            <Image style={{width:100,height:100}} source={{uri:BASE_URL.apiBaseUrl+item}}></Image>
        )
        views.push(control)
    })
    return views
  }



}





const styles = StyleSheet.create({
  item: {
    flexDirection: 'row',
    marginLeft: 15,
    borderBottomWidth: 0.5,
    borderBottomColor: '#e1e1e1',
    paddingTop: 14,
    paddingBottom: 13,
  },
  content: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingRight: 14,
  },
  label: {
    fontSize: 14,
  },
  inputStyle: {},
  value: {
    fontSize: 14,
    color: '#000',
    marginTop: 0,
  },
  placeholder: {
    fontSize: 14,
    color: '#a6a6a6',
  },
});
